import axios from 'axios'
import { Loading, Message } from 'element-ui';
// loading变量
let loadingInstance = null
import Vue from 'vue';
const newVue = new Vue
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_SIDDHI_API,
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 10000 // request timeout //接口太慢了,暂时关闭
})
// const clearTimeoutByUrl = (url, requestList) => {
//   for (let item in requestList) {
//     if (url === requestList[item]['url']) {
//       clearTimeout(requestList[item]['timeId']);
//     }
//   }
// }
service._requestCount = 0; // 累加请求次数
service._requestTimeIdList = [];
// request interceptor
service.interceptors.request.use(
  config => {
    config.headers["Accept"] = "*/*";
    // config.headers['Content-Type'] = 'multipart/form-data'
    // 如果接口请求小于200ms的话 那么就不显示loading
    // service._requestCount++;
    // const timeId = setTimeout(() => {
    //   loadingInstance = Loading.service({ text: '拼命加载中!' });
    // }, 200);
    // service._requestTimeIdList.push({
    //   timeId: timeId,
    //   url: config.url
    // });
    return config
  },
  error => {
    // do something with request error
    Message.error({
      message: error
    })
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    // service._requestCount--;
    // clear 200ms 后准备展示的loading
    // clearTimeoutByUrl(response.config.url, service._requestTimeIdList);
    // if (service._requestCount <= 0) {
    //   // loadingInstance = Loading.service();
    //   newVue.$nextTick(() => {
    //     if (loadingInstance) {
    //       loadingInstance.close();
    //     }
    //   })

    // }
    const res = response
    // if the custom code is not 20000, it is judged as an error.
    if (res.status !== 200 && res.status !== 201) {
      // return Promise.reject(new Error(res.message || 'Error'))
    } else {
      res.headers['Access-Control-Allow-Origin'] = '*'
      res.headers['server'] = "wso2-http-transport"
      res.headers['X-Requested-With'] = "XMLHttpRequest"
      return res
    }
  },
  error => {

    // service._requestCount--;
    // clearTimeoutByUrl(error.config.url, service._requestTimeIdList);
    // if (service._requestCount <= 0) { // 当全部的接口请求完毕后 关闭loading
    //   // loadingInstance = Loading.service();
    //   newVue.$nextTick(() => {
    //     if (loadingInstance) {
    //       loadingInstance.close();
    //     }
    //   })
    // }
    Message.error({
      message: error
    })
    console.log('err', error) // for debug
    return Promise.reject(error)
  }
)
export default service
